const { noticeApi } = require('../../../../utils/api');

Page({
  data: {
    notices: [],
    filteredNotices: [],
    loading: false,
    error: null,
    searchKeyword: '',
    currentFilter: 'all',
    isRefresherTriggered: false
  },

  onLoad() {
    console.log('全部通知页面加载');
    this.loadNotices();
  },

  onShow() {
    console.log('全部通知页面显示');
    // 页面显示时刷新数据
    this.loadNotices();
  },

  // 加载通知列表
  async loadNotices() {
    this.setData({ loading: true, error: null });
    
    try {
      const notices = await noticeApi.getAllNotices();
      console.log('获取全部通知成功:', notices);
      
      // 处理通知数据，添加格式化时间等
      const processedNotices = notices.map(notice => ({
        ...notice,
        formattedTime: this.formatTime(notice.createTime)
      }));
      
      this.setData({ 
        notices: processedNotices,
        filteredNotices: processedNotices,
        loading: false 
      });
      
      // 应用当前筛选
      this.filterAndSortNotices();
    } catch (error) {
      console.error('获取通知列表失败:', error);
      this.setData({ 
        error: '加载失败，请重试',
        loading: false 
      });
      
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    }
  },

  // 格式化时间
  formatTime(dateString) {
    if (!dateString) return '';
    
    const date = new Date(dateString);
    const now = new Date();
    const diff = now - date;
    
    // 小于1分钟
    if (diff < 60000) {
      return '刚刚';
    }
    // 小于1小时
    if (diff < 3600000) {
      return Math.floor(diff / 60000) + '分钟前';
    }
    // 小于1天
    if (diff < 86400000) {
      return Math.floor(diff / 3600000) + '小时前';
    }
    // 小于7天
    if (diff < 604800000) {
      return Math.floor(diff / 86400000) + '天前';
    }
    
    // 超过7天显示具体日期
    return date.toLocaleDateString();
  },

  // 搜索输入
  onSearchInput(e) {
    const keyword = e.detail.value;
    this.setData({ searchKeyword: keyword });
    this.applyFilter();
  },

  // 清除搜索
  clearSearch() {
    this.setData({ searchKeyword: '' });
    this.applyFilter();
  },

  // 筛选切换
  setFilter(e) {
    const filter = e.currentTarget.dataset.filter;
    this.setData({ currentFilter: filter });
    this.applyFilter();
  },

  // 应用筛选
  applyFilter() {
    const { notices, searchKeyword, currentFilter } = this.data;
    let filtered = [...notices];

    // 搜索筛选
    if (searchKeyword) {
      const keyword = searchKeyword.toLowerCase();
      filtered = filtered.filter(notice => 
        notice.title.toLowerCase().includes(keyword) ||
        notice.content.toLowerCase().includes(keyword)
      );
    }

    // 类型筛选
    if (currentFilter === 'top') {
      filtered = filtered.filter(notice => notice.isTop === 1);
    } else if (currentFilter === 'recent') {
      // 最近7天
      const sevenDaysAgo = new Date();
      sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
      filtered = filtered.filter(notice => {
        const noticeDate = new Date(notice.createTime);
        return noticeDate >= sevenDaysAgo;
      });
    }

    // 按时间排序（置顶的在前，然后按时间倒序）
    filtered.sort((a, b) => {
      if (a.isTop !== b.isTop) {
        return b.isTop - a.isTop; // 置顶的在前
      }
      return new Date(b.createTime) - new Date(a.createTime); // 时间倒序
    });

    this.setData({ filteredNotices: filtered });
  },

  // 点击通知项
  onNoticeTap(e) {
    const { noticeId } = e.currentTarget.dataset;
    console.log('点击通知ID:', noticeId);

    // 根据ID查找通知详情
    const notice = this.data.filteredNotices.find(n => n.noticeId == noticeId);
    if (notice) {
      wx.showModal({
        title: notice.title,
        content: notice.content,
        showCancel: false,
        confirmText: '知道了'
      });
    }
  },

  // 搜索输入
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    });
    this.filterAndSortNotices();
  },

  // 清除搜索
  clearSearch() {
    this.setData({
      searchKeyword: ''
    });
    this.filterAndSortNotices();
  },

  // 筛选器改变
  setFilter(e) {
    this.setData({
      currentFilter: e.currentTarget.dataset.filter
    });
    this.filterAndSortNotices();
  },

  // 筛选和排序通知
  filterAndSortNotices() {
    const { notices, searchKeyword, currentFilter } = this.data;
    let tempNotices = [...notices];

    // 搜索
    if (searchKeyword) {
      const keyword = searchKeyword.toLowerCase();
      tempNotices = tempNotices.filter(notice =>
        (notice.title && notice.title.toLowerCase().includes(keyword)) ||
        (notice.content && notice.content.toLowerCase().includes(keyword))
      );
    }

    // 筛选
    if (currentFilter === 'top') {
      tempNotices = tempNotices.filter(notice => notice.isTop === 1);
    } else if (currentFilter === 'recent') {
      const sevenDaysAgo = new Date();
      sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
      tempNotices = tempNotices.filter(notice => new Date(notice.createTime) > sevenDaysAgo);
    }

    // 排序：置顶优先，然后按时间倒序
    tempNotices.sort((a, b) => {
      if (a.isTop === 1 && b.isTop !== 1) return -1;
      if (a.isTop !== 1 && b.isTop === 1) return 1;
      return new Date(b.createTime) - new Date(a.createTime);
    });

    this.setData({
      filteredNotices: tempNotices
    });
  },

  // 查看通知详情
  viewNoticeDetail(e) {
    const notice = e.currentTarget.dataset.notice;
    if (notice) {
      wx.showModal({
        title: '通知详情',
        content: `标题：${notice.title}\n\n内容：${notice.content}\n\n发布时间：${notice.formattedTime}\n班级ID：${notice.classId}\n发布者：${notice.publisherUserId}`,
        showCancel: false,
        confirmText: '知道了'
      });
    }
  },

  // 创建通知
  createNotice() {
    wx.navigateTo({
      url: '/pages/class/notice/create-notice/index'
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadNotices().then(() => {
      wx.stopPullDownRefresh();
    }).catch(() => {
      wx.stopPullDownRefresh();
    });
  }
});
